package com.etoak.service.impl;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.redis.service.RedisService;
import com.etoak.common.web.context.LoginUserContext;
import com.etoak.entity.Cart;
import com.etoak.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisService redisService;

    @Override
    public void saveOrUpdate(Cart cart) {
        redisService.hset(getCartKey(),cart.getDishId().toString(), JSONUtil.toJsonStr(cart));
    }

    @Override
    public List<Cart> getList() {
        return redisService.hvals(getCartKey())
                .stream().map(json -> JSONUtil.toBean(json, Cart.class)).toList();
    }

    @Override
    public void delete(List<String> ids) {
        redisService.hdel(getCartKey(),ids.toArray(new String[]{}));
    }

    private String getCartKey() {
        return CommonConstant.USER_CART_RADIS_KEY_PREFIX + LoginUserContext.getUserId();
    }
}
